

import "../../css/style.css"
import "../../css/userCenterSpace/userCenterSpace.css"
import "../../css/IM/IM.css"
import main from "./component/main.js"
import chat from "./component/chat.js"
import Client from "./chatClient.js"
import { handleDate, getUserInfor, getPar, getMyId } from "./component/untils.js"
import loading from "./component/loading.js"
import { smileys } from "./configs.js"
import modal from "./component/modal.js"
import Sact from "sact"
import setting from "./component/setting/setting.js"

window.sact = Sact;
//表情包
window.smileys = smileys;
//用户信息
window.userInfor = {};
//总控制台
let root;



function init(id, callback) {
    try {
        const appId = 'YN8GaiI9Ms5Wez54j189e6Dc-gzGzoHsz';
        const appKey = 'UbHVeq41SOlOfmOoUFbwAXY8';
        const server = 'https://im.jiandanmaimai.cn';
        AV.init({ appId, appKey, serverURL: server });
        window.realtime = new AV.Realtime({ appId, appKey, server, plugins: AV.TypedMessagesPlugin });

        login(id, callback);
    }
    catch (e) {
        root.data.loadingMsg = "加载组件失败，请检查您的网络!";
    }
}
//登录函数
function login(id, callback) {
    window.client = new Client(id, {
        //登录成功
        whenInited(c) {
            let { conversationsList } = c;
            root.data.loadingMsg = "登录成功";
            setTimeout(() => {
                //加载用户资料
                root.data.loadingMsg = "加载用户数据中";
                getUserInfor(conversationsList)
                    .then((res) => {
                        root.init(conversationsList);
                        callback();
                    })
            }, 500)
        },
        //收到消息时
        whenMessage(m, c) {
            for (let i of root.data.chatlist) {
                if (i.id === c.id) {
                    let [lastMessage, lastTime, timestamp] = getlastMessage(c);
                    i.lastMessage = lastMessage;
                    i.lastTime = lastTime;
                    i.timestamp = timestamp;
                    //如果当前会话和接到消息的会话相同就不用更新主界面了
                    if (!(client.imaTaiKai === c)) {
                        i.waitNum += 1;
                    }
                }
            }
        },
        //登录失败
        failCallback(e) {
            root.data.loadingMsg = "登录失败！请检查网址是否正确后刷新重试";
        },
        whenInvited(p, e) {
            root.showMessage(`你已被用户：${p.invitedBy}邀请进一个新聊天`);
            root._addchat(e);
        },
    });
}
//总控制台
window.root = root = new Sact({
    ele: "#root",
    template: `<div id="root" class="chatBackgroud">
    <loading s-if="show.loading" :msg="loadingMsg"></loading>
    <main :show="show.main" @addchat="addChat"  :chatlist="chatlist" @changechat="changechat"></main>
    <chat s-if="show.chat" @backtomain="backToMain" :key="showId" @gotomore="goToMore"></chat>
    <modal :show="show.newMessage" :ok="close" :title="newMessage"></modal>
    <im-setting></im-setting>
</div>`,
    component: {
        main, chat, loading, modal,setting
    },
    //加载完毕
    mounted() {
        window.showMessage = this.showMessage;
        getMyId().then((id) => {
            init(String(id), () => {
                let newsaion = getPar("newConversationId");
                if (newsaion) {
                    this.addChat(newsaion, (e) => {
                        this.changechat(e.id);
                    });
                }
            });
        }).catch(() => {
            root.data.loadingMsg = "登录失败！请检查网址是否正确后刷新重试";
        })
    },
    data: {
        logined: false,
        messageList: [],
        msg: "",
        chatlist: [],
        show: {
            main: false,
            chat: false,
            loading: true,
            newMessage: false,
        },
        showId: "",
        chatname: "",
        loadingMsg: "登陆中",
        newMessage: "",
    },
    method: {
        //初始化
        init(conversationsList) {
            this.data.show.loading = false;
            this.data.show.main = true;
            this.freshen(conversationsList);
        },
        //刷新所有的聊天信息
        freshen(conversationsList = client.conversationsList) {
            this.data.chatlist = conversationsList.map((v) => {
                return doChat(v);
            });
            this.data.chatlist.sort((a, b) => {
                return a.timestamp - b.timestamp;
            })
        },
        //增加一个新的聊天
        addChat(id, callback) {
            client.createNewConversation(id, (v) => {
                for (let i of this.data.chatlist) {
                    if (i.id === v.id) {
                        callback && callback(v);
                        return;
                    }
                }
                this._addchat(v, callback);
            })
        },
        _addchat(v, callback) {
            getUserInfor([v]).then(() => {
                let res = doChat(v);
                this.data.chatlist.push(res);
                callback && callback(v);
            })
        },
        //改变当前的聊天
        changechat(id, name) {
            client.changeConversation(id);
            client.imaTaiKai.waitNum = 0;
            this.data.showId = id;
            this.data.show.chat = true;
            this.data.show.main = false;
        },
        //回到主界面
        backToMain() {
            client.changeConversation();
            this.data.show.main = true;
            this.data.show.chat = false;
            this.showId = "null";
        },
        //显示全局提示信息
        showMessage(msg) {
            this.data.show.newMessage = true;
            this.data.newMessage = msg;
        },
        //关闭全局显示信息
        close() {
            this.data.show.newMessage = false;
        },
        //打开聊天详情
        goToMore() {

        }
    }
})
function doChat(v) {
    let [lastMessage, lastTime, timestamp] = getlastMessage(v);
    v.chatName = getName(v);
    let res = {
        "name": v.chatName,
        "lastMessage": lastMessage,
        "id": v.id,
        "members": v.members,
        "lastTime": lastTime,
        "waitNum": v.unreadMessagesCount,
        "timestamp": timestamp,
    }
    return res;
}
function getName(v) {
    let list = v.members;
    list.splice(list.indexOf(client.uid), 1);
    if (list.length === 1) {
        return userInfor[list[0]].username;
    }
    else {
        return v.name;
    }
}
function getlastMessage(chat) {
    let msg = chat.lastMessage;
    if (msg) {
        return [msg._lctext || msg.content, handleDate(msg._timestamp), msg._timestamp.getTime()];
    } else {
        return ["", ""]
    }
}

if (module.hot) {
    module.hot.accept('./print.js', function () {
        console.log('Accepting the updated printMe module!');
        printMe();
    })
}